<?php
namespace App\Common\Server\Api\Gateway\ApiRequest\ApiData;

use App\Common as com;
use App as nameApp;
use App\Common\Server\Api\Gateway\ApiRequest as nameApiRequest;
use App\Common\Server\Api as nameApi;

class ApiParam extends nameApi\Base {

	/**
	 * api参数数据
	 * @var array
	 */
	private array $apiParam = [];

	/**
	 * 是否存在数据
	 * @param string $name 数据名
	 * @return bool 是否存在
	 */
	public function isExists( string $name ):bool {
		return isset( $this->apiParam[ $name ] );
	}
	
	/**
	 * 获取数据
	 * @param string|null $name [{string}]获取指定值 [{null}]获取所有
	 * @param null $default 默认值 [null][默认]
	 * @return mixed|array|null
	 */
	public function get( string $name = null, $default = null ):mixed {
		if( null !== $name ){
			return $this->apiParam[ $name ] ?? $default;
		}else{
			return $this->apiParam;
		}
	}

	/**
	 * 设置数据
	 * @param array|string $value1 [{string}]设置指定值 [{array}]覆盖数据
	 * @param mixed $value2
	 * @return static
	 * @throws
	 */
	public function set( array|string $value1 = [], mixed $value2 = null ):static {
		if( is_array( $value1 ) ){
			$this->apiParam = $value1;
		}elseif( null !== $value2 ){
			$this->apiParam[ $value1 ] = $value2;
		}else{
			throw com\Lib\Err\Exception::makeOfNew( 'apiParam格式错误，请检查', com\Lib\Err\Code::$sysFunParamError );
		}
		//
		return $this;
	}

	/**
	 * 验证数据并返回验证器结果
	 * @param array $rules
	 * @param array $message
	 * @return \Hyperf\Contract\ValidatorInterface
	 */
	public function verifyData( array $rules, array $message = [] ):\Hyperf\Contract\ValidatorInterface {
		return com\Lib\Hyperf::newValidation()->make( $this->apiParam, $rules, $message );
	}

	/**
	 * 验证数据
	 * @param array $rules
	 * @param array $message
	 * @return \Hyperf\Contract\ValidatorInterface|null [null]验证通过
	 */
	public function verifyDataOrNull( array $rules, array $message = [] ):?\Hyperf\Contract\ValidatorInterface {
		$reValidatorRes = $this->verifyData( $rules, $message );
		return $reValidatorRes->fails() ? $reValidatorRes : null;
	}

}
